package com.shoulder.boot.acl.utils;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.shoulder.boot.acl.dto.ClientQueryDTO;
import com.shoulder.boot.acl.entity.Oauth2RegisteredClient;
import com.shoulder.boot.acl.vo.ClientVo;
import com.shoulder.core.utils.JsonUtils;
import com.shoulder.mybatis.utils.PageUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;

public class ClientUtils implements PageUtils<Oauth2RegisteredClient, ClientVo> {

    public static ClientUtils buildUtils() {
        return new ClientUtils();
    }

    @Override
    public ClientVo toVo(Oauth2RegisteredClient entity) {
        ClientVo vo = new ClientVo();
        BeanUtils.copyProperties(entity, vo);
        if (!ObjectUtils.isEmpty(vo.getTokenSettings())) {
            Map<String, Object> tokenSettings = JsonUtils.json2Bean(vo.getTokenSettings(), Map.class);
            ArrayList list = (ArrayList) tokenSettings.get("settings.token.access-token-time-to-live");
            vo.setTokenValidTime(((Double) list.get(1)).longValue());
            ArrayList list1 = (ArrayList) tokenSettings.get("settings.token.refresh-token-time-to-live");
            vo.setRefreshTokenValidTime(((Double) list1.get(1)).longValue());
        }

        if (!ObjectUtils.isEmpty(vo.getClientSettings())) {
            Map<String, Object> clientSettings = JsonUtils.json2Bean(vo.getClientSettings(), Map.class);
            vo.setRequireAuthorizationConsent((Boolean) clientSettings.get("settings.client.require-authorization-consent"));
        }
        vo.setAuthorizationGrantTypes(Arrays.asList(vo.getAuthorizationGrantType().split(",")));
        vo.setClientAuthenticationMethods(Arrays.asList(vo.getClientAuthenticationMethod().split(",")));
        vo.setRedirectUri(vo.getRedirectUris());

        return vo;
    }

    public static LambdaQueryWrapper<Oauth2RegisteredClient> buildQueryWrapper(ClientQueryDTO queryDTO) {
        LambdaQueryWrapper<Oauth2RegisteredClient> queryWrapper = new LambdaQueryWrapper<Oauth2RegisteredClient>().orderByDesc(Oauth2RegisteredClient::getClientIdIssuedAt);
        queryWrapper.like(!ObjectUtils.isEmpty(queryDTO.getClientId()), Oauth2RegisteredClient::getClientId, queryDTO.getClientId());
        return queryWrapper;
    }
}